import React from 'react';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import {Card} from 'antd';
import queryString from 'query-string';
import PostFilter from './PostFilter';
import PostTable from './PostTable';
import ContentWrapper from '../layouts/ContentWrapper';
import styles from './Index.less';

@connect(state => ({
  loading: state.loading,
  postCat: state.postCat,
  post: state.post,
}))
export default class Index extends React.PureComponent {

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'postCat/getAll',
    })
  }

  handleChange = values => {
    const {location: {pathname, search}, dispatch} = this.props;
    const query = queryString.parse(search);
    const payload = {
      ...query,
      ...values,
    };

    dispatch(routerRedux.push({
      pathname,
      search: queryString.stringify(payload),
    }));
  };

  handleFilterChange = values => {
    this.handleChange({
      ...values,
      page: 1,
    });
  };

  handleTableChange = (pagination, filters, sorter) => {
    let params = {
      page: pagination.current,
      per_page: pagination.pageSize,
    };
    for (let k in filters) {
      if (filters[k]) {
        params[k] = filters[k];
      }
    }
    if (sorter.field) {
      params = {
        ...params,
        sort: sorter.field,
        order: sorter.order,
      };
    }

    this.handleChange(params);
  };

  render() {
    const {location, dispatch, loading, postCat: {list: postCatList}, post: {list, pagination, selectedRowKeys}} = this.props;
    const query = queryString.parse(location.search);

    const filterProps = {
      dispatch,
      list: postCatList,
      query,
      onFilterChange: this.handleFilterChange,
    };

    const tableProps = {
      dispatch,
      loading,
      list,
      pagination,
      selectedRowKeys,
      query,
      onTableChange: this.handleTableChange,
    };

    return (
      <ContentWrapper>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <PostFilter {...filterProps} />
            <PostTable {...tableProps} />
          </div>
        </Card>
      </ContentWrapper>
    );
  }
}
